package cn.iocoder.yudao.module.bpm.service.journalapply;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.bpm.api.task.BpmProcessInstanceApi;
import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import cn.iocoder.yudao.module.bpm.controller.admin.journal.vo.JournalSaveReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.journalapply.vo.JournalApplyPageReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.journalapply.vo.JournalApplySaveReqVO;
import cn.iocoder.yudao.module.bpm.dal.dataobject.journalapply.JournalApplyDO;
import cn.iocoder.yudao.module.bpm.dal.dataobject.journalapplydetail.JournalApplyDetailDO;
import cn.iocoder.yudao.module.bpm.dal.mysql.journalapply.JournalApplyMapper;
import cn.iocoder.yudao.module.bpm.dal.mysql.journalapplydetail.JournalApplyDetailMapper;
import cn.iocoder.yudao.module.bpm.enums.task.BpmProcessInstanceStatusEnum;
import cn.iocoder.yudao.module.bpm.service.journal.JournalService;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants.JOURNAL_APPLY_NOT_EXISTS;
import static cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants.OA_LEAVE_NOT_EXISTS;

/**
 * 期刊申请 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class JournalApplyServiceImpl implements JournalApplyService {

    public static final String PROCESS_KEY = "journalApply";

    @Resource
    private JournalApplyMapper journalApplyMapper;

    @Resource
    private JournalService journalService;

    @Resource
    private JournalApplyDetailMapper journalApplyDetailMapper;

    @Resource
    private BpmProcessInstanceApi processInstanceApi;

    @Override
    public Long createJournalApply(Long userId,JournalApplySaveReqVO createReqVO) {
        // 插入
        JournalApplyDO journalApply = BeanUtils.toBean(createReqVO, JournalApplyDO.class);
        journalApplyMapper.insert(journalApply);

        createJournalApplyDetailList(journalApply.getId(),createReqVO.getJournalApplyDetails());


        if(createReqVO.getOperateFlag().equals("submit")){
            String processInstanceId = processInstanceApi.createProcessInstance(userId,
                    new BpmProcessInstanceCreateReqDTO().setProcessDefinitionKey(PROCESS_KEY)
                            //.setVariables(processInstanceVariables)
                            .setBusinessKey(String.valueOf(journalApply.getId()))
                            .setStartUserSelectAssignees(createReqVO.getStartUserSelectAssignees())).getCheckedData();
            // 将工作流的编号，更新到 OA 请假单中
            journalApplyMapper.updateById(new JournalApplyDO().setId(journalApply.getId())
                    .setProcessInstanceId(processInstanceId)
                    .setStatus(BpmProcessInstanceStatusEnum.RUNNING.getStatus()));
        }else {
            journalApplyMapper.updateById(new JournalApplyDO().setId(journalApply.getId())
                    .setStatus(BpmProcessInstanceStatusEnum.NOT_START.getStatus()));
        }

        // 返回
        return journalApply.getId();
    }

    @Override
    public void updateJournalApply(Long userId,JournalApplySaveReqVO updateReqVO) {
        // 校验存在
        validateJournalApplyExists(updateReqVO.getId());
        // 更新
        JournalApplyDO updateObj = BeanUtils.toBean(updateReqVO, JournalApplyDO.class);
        journalApplyMapper.updateById(updateObj);

        updateJournalApplyDetailList(updateObj.getId(),updateReqVO.getJournalApplyDetails());

        if(updateReqVO.getOperateFlag().equals("submit")){
            String processInstanceId = processInstanceApi.createProcessInstance(userId,
                    new BpmProcessInstanceCreateReqDTO().setProcessDefinitionKey(PROCESS_KEY)
                            //.setVariables(processInstanceVariables)
                            .setBusinessKey(String.valueOf(updateObj.getId()))
                            .setStartUserSelectAssignees(updateReqVO.getStartUserSelectAssignees())).getCheckedData();
            // 将工作流的编号，更新到 OA 请假单中
            journalApplyMapper.updateById(new JournalApplyDO().setId(updateObj.getId())
                    .setProcessInstanceId(processInstanceId)
                    .setStatus(BpmProcessInstanceStatusEnum.RUNNING.getStatus()));
        } else {
            journalApplyMapper.updateById(new JournalApplyDO().setId(updateObj.getId())
                    .setStatus(BpmProcessInstanceStatusEnum.NOT_START.getStatus()));
        }
    }

    @Override
    public void deleteJournalApply(Long id) {
        // 校验存在
        validateJournalApplyExists(id);
        // 删除
        journalApplyMapper.deleteById(id);

        deleteJournalApplyDetailList(id);
    }

    private void validateJournalApplyExists(Long id) {
        if (journalApplyMapper.selectById(id) == null) {
            throw exception(JOURNAL_APPLY_NOT_EXISTS);
        }
    }

    @Override
    public JournalApplyDO getJournalApply(Long id) {
        return journalApplyMapper.selectById(id);
    }

    @Override
    public PageResult<JournalApplyDO> getJournalApplyPage(JournalApplyPageReqVO pageReqVO) {
        return journalApplyMapper.selectPage(pageReqVO);
    }


    private void createJournalApplyDetailList(Long applyId, List<JournalApplyDetailDO> list) {
        if(CollectionUtils.isEmpty(list)) {
            return;
        }
        if (list != null) {
            list.forEach(o -> {
                o.setApplyId(applyId);
                o.setId(null);
            });
        }
        journalApplyDetailMapper.insertBatch(list);
    }

    private void updateJournalApplyDetailList(Long applyId, List<JournalApplyDetailDO> list) {
        if(CollectionUtils.isEmpty(list)) {
            return;
        }
        journalApplyDetailMapper.deleteByApplyId(applyId);
        list.forEach(o -> o.setId(null).setUpdater(null).setUpdateTime(null)); // 解决更新情况下：1）id 冲突；2）updateTime 不更新
        createJournalApplyDetailList(applyId, list);
    }

    private void deleteJournalApplyDetailList(Long applyId) {
        journalApplyDetailMapper.deleteByApplyId(applyId);
    }

    @Override
    public void updateLeaveStatus(Long id, Integer status) {
        validateLeaveExists(id);
        journalApplyMapper.updateById(new JournalApplyDO().setId(id).setStatus(status));

        if(status.equals(BpmProcessInstanceStatusEnum.APPROVE.getStatus())){
            journalApplyDetailMapper.getJournalApplyDetailList(id).forEach(o -> {
                journalService.updateJournal(new JournalSaveReqVO().setId(o.getJournalId()).setStatus(1));
            });
        }
    }
    private void validateLeaveExists(Long id) {
        if (journalApplyMapper.selectById(id) == null) {
            throw exception(OA_LEAVE_NOT_EXISTS);
        }
    }

}